﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class LevelSelectController : MonoBehaviour {
	public GameObject levelItemPref;
	public UIScrollView scroll;
	public UIGrid grid;
	public float xPosition;
	//private int NUM_OF_LEVEL = 10;
	private List<LevelItem> listLevel;
	// Use this for initialization
	void Start () {
		parserLevlData ();
		addLevel (listLevel);
		StartCoroutine (tweenPopup ());
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	private void addLevel (List<LevelItem> listLevel) {
		for (int i=0; i < listLevel.Count; i++) {
			GameObject go = NGUITools.AddChild (grid.gameObject, levelItemPref);
			LevelItemController controller = go.GetComponent<LevelItemController> ();
			controller.setLevelName (listLevel [i].level_name);
			controller.sceneName = listLevel [i].scene_name;
			go.GetComponent <UIButton> ().onClick.Add(new EventDelegate(this,"onItemLevelClcik"));
		}
		grid.Reposition ();
		scroll.ResetPosition ();
	}

	// On level item click 
	private void onItemLevelClcik () {
		Application.LoadLevel (UIButton.current.GetComponent<LevelItemController> ().sceneName);
	}
	private void parserLevlData () {
		TextAsset textAsset = Resources.Load("Gamedata/level_data") as TextAsset;
		listLevel = LitJson.JsonMapper.ToObject<List<LevelItem>> (textAsset.text);
	}

	private IEnumerator tweenPopup () {
		yield return new WaitForSeconds (0.3f);
		LeanTween.moveLocalY (gameObject,xPosition,0.5f).setEase(LeanTweenType.easeOutBack);
	}
}
